# -*- coding: utf-8 -*-
import requests
import random
import json
from hashlib import md5
import os


def transApi(appid, appkey, from_lang, to_lang, query):
    try:
        endpoint = 'http://api.fanyi.baidu.com'
        path = '/api/trans/vip/translate'
        url = endpoint + path

        def make_md5(s, encoding='utf-8'):
            return md5(s.encode(encoding)).hexdigest()

        salt = random.randint(32768, 65536)
        sign = make_md5(appid + query + str(salt) + appkey)

        # Build request
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

        # Send request
        r = requests.post(url, params=payload, headers=headers)
        result = r.json()

        # Show response
        # print(json.dumps(result, indent=4, ensure_ascii=False))
        return_obj = json.dumps(result, indent=4, ensure_ascii=False)
        dict = json.loads(return_obj)
        return dict["trans_result"]
    except Exception:
        return ""


def tran_file(appid, appkey, from_lang, to_lang, file_path):
    context = ""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.read()
    list = lines.split("\n")
    list = [x for x in list if x != ""]
    zoneNum = len(list)
    doneNum = 0
    for line in list:
        doneNum += 1
        result_list = transApi(appid, appkey, from_lang, to_lang, line)
        for item in result_list:
            context += item["dst"] + '\n'
            print(context)
        print(">> 翻译进度: %.2f%% [%s/%s]" % (doneNum / zoneNum * 100, doneNum, zoneNum))
    return context


def write_file(file_path,context):
    # 写入文件名
    filepath, tmpfilename = os.path.split(file_path)
    # # 创建文件夹
    # folder = os.path.exists('./译文')
    # if not folder:
    #     os.makedirs('./译文')
    write_file_path = './' + '【译文】' + tmpfilename.split('.')[0] + '.txt'
    with open(write_file_path, mode='w', encoding="utf-8") as f:
        f.write(context)
    print(write_file_path + '>>写入成功')


if __name__ == '__main__':
    appid = 'appid'
    appkey = 'appkey'
    from_lang = 'jp'
    to_lang = 'zh'
    file_path= '../测试文本输入JP.txt'
    context = tran_file(appid, appkey, from_lang, to_lang, file_path)
    write_file(file_path,context)
